import type { Channel, Articles } from "@/types/data"
import type { HomeAction } from "@/types/store"

type HomeState = {
  userChannel: Channel[]
  channelArticles: {
    [key: number]: Articles
  }
}
const initialState: HomeState = {
  userChannel: [],
  channelArticles: {},
}

const Home = (state = initialState, action: HomeAction): HomeState => {
  switch (action.type) {
    case "home/getUserChannel":
      return {
        ...state,
        userChannel: action.payload,
      }
    case "home/getChannelArticles":
      const curChannelArticles = state.channelArticles[
        action.payload.channelId
      ] ?? {
        pre_timestamp: null,
        results: [],
      }
      const {
        channelId,
        data: { pre_timestamp, results },
      } = action.payload

      return {
        ...state,
        channelArticles: {
          ...state.channelArticles,
          // 修改当前频道对应的文章列表数据
          [channelId]:
            action.actionType === "append"
              ? {
                  pre_timestamp,
                  // 追加文章列表数据
                  results: [...curChannelArticles.results, ...results],
                }
              : { pre_timestamp, results: [...results] },
        },
      }
    default:
      return state
  }
}

export default Home
